import { Table, Input, Button, Col, Row, Form, Select, Pagination, message, Space } from 'antd';
import { useEffect, useState } from 'react';
import styles from './index.module.scss'
import { useNavigate } from 'react-router-dom';
import { TimeConversion } from "@/utils";
import { getNoticeAll, getNotiveUnreadAll, changeNotiveStatus } from '@/service'
import { setMessageCount } from '@/reducers/main';
import { useDispatch } from 'react-redux';
import { useTranslation } from 'react-i18next';

export default (props) => {
    const [form] = Form.useForm(); // 创建表单实例
    const [messageApi, contextHolder] = message.useMessage();
    const [noticeData, setNoticeData] = useState([]);
    const { t, i18n } = useTranslation();
    const initState = () => ({
        total: '',
        pageSize: 10,
        pageNo: 1,
        noticeList: [],
        loading: false
    }),
        navigate = useNavigate(),
        dispatch = useDispatch(),
        [state, setState] = useState(initState);
    const columns = [
        {
            title: t('menu.notiveALl.table.order'),
            width: 80,
            render: (text, record, index) => index + 1,
        },
        {
            title: t('menu.notiveALl.table.title'),
            dataIndex: 'title',
        },
        {
            title: t('menu.notiveALl.table.content'),
            dataIndex: 'content',
            width: 300,
            ellipsis: true,
        },
        {
            title: t('menu.notiveALl.table.acceptTime'),
            dataIndex: 'createTime',
            render(_col, item) {
                return TimeConversion(item.createTime)
            },
        },
        {
            title: t('menu.notiveALl.table.operation'),
            key: 'operation',
            fixed: 'right',
            align: 'center',
            with: 100,
            render: (_, record) => (
                <Space size="middle">
                    {record.isRead ? (
                        <span className={styles.readLabel}>{t('menu.notiveALl.table.read')}</span>
                    ) : (
                        <Button
                            type='primary'
                            style={{ borderRadius: '20px' }}
                            onClick={() => markAsRead(record)} className={styles.markAsReadButton}>
                            {t('menu.notiveALl.table.readBtn')}
                        </Button>
                    )}
                </Space>
            ),
        },
    ];
    const markAsRead = async (record) => {
        let params = {
            messageId: record?.messageId
        }
        const res = await changeNotiveStatus(params);
        const { code, message } = res;
        if (code == 0) {
            const updatedData = (state.noticeList || []).map(item => {
                if (item.messageId === record.messageId) {
                    return { ...item, isRead: 1 };
                }
                return item;
            });
            setState((o) => ({ ...o, noticeList: updatedData }));
            getNoticeList();
            getUnReadList();
        } else {
            messageApi.open({
                type: 'error',
                content: message,
            });
        }
    };
    const getUnReadList = async () => {
        const res = await getNotiveUnreadAll();
        const { code, message, data } = res;
        if (code == 0) {
            setNoticeData(data);
        } else {
            messageApi.open({
                type: 'error',
                content: message,
            });
        }
    };
    const handlePageChange = (page) => {
        setState(prevParams => ({ ...prevParams, pageNo: page }));
    };
    const handlePageSizeChange = (pageNo, pageSize) => {
        setState(prevParams => ({ ...prevParams, pageNo, pageSize }));
    };
    const goBack = () => {
        navigate('/');
    }
    const getNoticeList = () => {
        let params = {
            pageNo: state.pageNo,
            pageSize: state.pageSize
        }
        setState(prevState => ({ ...prevState, loading: true }));
        getNoticeAll(params).then(res => {
            if (res.code == 0) {
                setState(o => ({
                    ...o,
                    noticeList: res?.data?.records || [],
                    total: res?.data?.total || 0,
                    loading: false
                }));
            } else {
                messageApi.open({
                    type: 'error',
                    content: res?.msg,
                });
                setState(prevState => ({ ...prevState, loading: false }));
            }
        }).catch(e => {
            messageApi.open({
                type: 'error',
                content: e?.msg,
            });
            setState(prevState => ({ ...prevState, loading: false }));
        });
    }
    useEffect(() => {
        const num = noticeData.length || 0;
        dispatch(setMessageCount(num));
    }, [noticeData]);
    useEffect(() => {
        getUnReadList();
    }, [])
    useEffect(() => {
        getNoticeList();
    }, [state.pageNo, state.pageSize, i18n.language])
    return (
        <div className='page-container'>
            <div className={styles.content}>
                <div className={styles.tableCount}>
                    <Row className={styles.titBlock}>
                        <Col span={12}>
                            <div className='custom-title'>{t('menu.notiveALl.title')}</div>
                        </Col>
                        <Col span={12} className={styles.RightBlcok}>
                            <Button type='primary' className='custom-btn-back' onClick={goBack}>{t('common.goback.text')}</Button>
                        </Col>
                    </Row>
                    <Table loading={state.loading} rowKey={'id'} className='custom-table' rowClassName={(record) =>
                        record.isRead === 0 ? 'unread-row' : 'read-row'
                    } pagination={false} columns={columns} dataSource={state.noticeList} />
                    <div className='custom-Pagination'>
                        <Pagination
                            total={state?.total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={(totalNum) => t('common.pagination.totalNum', { totalNum })}
                            align="center"
                            current={state?.pageNo}
                            defaultPageSize={state?.pageSize}
                            onChange={handlePageChange}
                            onShowSizeChange={handlePageSizeChange}
                        />
                    </div>
                </div>
            </div>
            {contextHolder}
        </div>
    )
}